import twitter
import conf
from model import *

tw_consumer_key=conf.TWITTER_CONSUMER_KEY
tw_consumer_secret=conf.TWITTER_CONSUMER_SECRET
tw_access_token_key=conf.TWITTER_ACCESS_TOKEN_KEY
tw_access_token_secret=conf.TWITTER_ACCESS_TOKEN_SECRET

def get_info(topic,message_number=5):
    api=twitter.Api(consumer_key=tw_consumer_key,consumer_secret=tw_consumer_secret,
                access_token_key=tw_access_token_key,access_token_secret=tw_access_token_secret,cache=None)
    filter=api.GetSearch(term=topic.title ,per_page=message_number)
    info_to_return=[]
    for tweet in filter:
        url=get_tweet_url(tweet)
        infos=Info.find_by_link(url)
        if not len(infos)==0:
            info=infos[0]
        else:
            info=Info(text=tweet.text,link=url)
            info.put()
        info_to_return.append(info)
    return info_to_return

def get_tweet_url(status):
    return "http://twitter.com/#!/%s/status/%s"%(status.user.screen_name,status.id)
